import React, { useEffect, useState, useCallback, useMemo } from 'react';
import { history } from 'umi'
import { connect } from 'umi';
import { useDeepCompareEffect } from 'react-use';
import { Card, Tabs, Button, Modal, Table, Typography, message } from 'antd';
import xss from 'xss';
import Icon from '@/components/IconPro';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import { withRoutePage } from '@/utils/enhanceUtils';
import routerReplace from '@/utils/routerReplace';
import { Pagination } from '@/components';
import { useDictionary } from '@/hooks';
import { parseLocation } from '@/utils/utils';
import { newTabProps } from '@/utils/tab';

import useSubscribeMsg from '@/hooks/useSubscribeMsg';
import Msg from '@/hooks/useSubscribeMsg/Msg';
import styles from './Message.less';

const { TabPane } = Tabs;
const { Paragraph } = Typography;

const Message = ({ userMessage, loading, location, dispatch }) => {
    const { query } = location;
    const [activeKey, setActiveKey] = useState(query.key || 'all');
    const [selectedRow, setSelectRow] = useState([]);
    const [tabActionLoading, setTabActionLoading] = useState(false);
    const [allNoticeData, setAllNoticeData] = useState([]);
    const [unreadNoticeData, setUnreadNoticeData] = useState([]);
    const [readNoticeData, setReadNoticeData] = useState([]);
    const [allNoticePageTotal, setAllNoticePageTotal] = useState([]);
    const [readNoticePageTotal, setReadNoticePageTotal] = useState([]);
    const [unreadNoticePageTotal, setUnreadNoticePageTotal] = useState([]);

    const [messageResource = []] = useDictionary('messageResource');

    const getNoticeList = useCallback(() => {
        let resourceList = [];
        try {
            resourceList = JSON.parse(query.messageModuleTypes || []);
        } catch (e) {
            resourceList = [];
        }
        dispatch({
            type: 'userMessage/getNoticeList',
            payload: {
                // eslint-disable-next-line no-nested-ternary
                readState: query.key === '0' ? 0 : query.key === '1' ? 1 : -1,
                queryList: true,
                pageNo: query.current || 1,
                pageSize: query.pageSize || 10,
                resourceList
            },
            callback: () => {
                setTabActionLoading(false);
            }
        });
    }, [dispatch, query]);

    useEffect(() => {
        setTabActionLoading(true);
    }, []);

    const selectedRowsIndex = useMemo(() => {
        const getSelectedNotice = type =>
            userMessage[type].rows
                .map(item => {
                    if (selectedRow.includes(item.businessId)) {
                        return item.businessId;
                    }

                    return null;
                })
                .filter(item => item !== null);

        switch (activeKey) {
            case 'all': {
                return getSelectedNotice('allNoticeData');
            }
            case '0': {
                return getSelectedNotice('unreadNoticeData');
            }
            case '1':
                return getSelectedNotice('readNoticeData');
            default:
                return [];
        }
    }, [activeKey, selectedRow, userMessage]);

    const { subContent } = useSubscribeMsg({ subType: [Msg.notice] });

    useEffect(() => {
        getNoticeList();
    }, [query, getNoticeList]);

    // 根据URl获取列表数据, 需要query作为刷新条件请勿删除
    useEffect(() => {
        if (subContent?.type === 'notice') {
            getNoticeList();
        }
    }, [subContent, getNoticeList]);

    // 重置URL
    const handleReplacePage = param => {
        routerReplace({ query: { ...query, ...param } });
    };

    // 切换Tab
    const handleChangedTabs = key => {
        setActiveKey(key);
        setSelectRow([]);
        setTabActionLoading(true);
        handleReplacePage({ key, current: 1, messageModuleTypes: JSON.stringify([]) });
    };

    // 分页
    const handlePaginationChange = pagination => {
        setSelectRow([]);
        handleReplacePage({ current: pagination?.current, pageSize: pagination?.pageSize });
    };

    // 处理表格过滤
    const handleTableChange = (pagination, filters) => {
        if (filters && filters.noticeResourceName) {
            handleReplacePage({
                current: 1,
                messageModuleTypes: JSON.stringify(filters.noticeResourceName)
            });
        }
    };

    // 清空已选，重新获取消息数量和重新获取消息列表
    const refreshNotice = () => {
        setSelectRow([]);
        getNoticeList();
    };

    // 标记为已读
    const markAsRead = (rows, quietness) => {
        dispatch({
            type: 'userMessage/setMarkAsRead',
            payload: {
                businessIds: rows
            },
            callback: msg => {
                if (!quietness) {
                    message.success(msg);
                }
                refreshNotice();
            }
        });
    };

    // 全部标记为已读
    const markAllAsRead = () => {
        dispatch({
            type: 'userMessage/setMarkAllAsRead',
            callback: () => {
                refreshNotice();
            }
        });
    };

    const columns = [
        {
            title: '标题',
            dataIndex: 'messageTitle',
            key: 'messageTitle',
            width: '50%',
            render: (text, record) => (
                <div
                    style={{
                        position: 'relative',
                        paddingRight: '68px'
                    }}
                >
                    {record.readState === 0 && <i className={styles.wnNewCircle}></i>}
                    <p
                        onClick={() => {
                            if (record.readState !== 1) {
                                markAsRead([record.businessId], true);
                            }
                            if (record.targetUrl) {
                                const [pathname, redirectQuery] = parseLocation({ pathname: record.targetUrl });
                                history.push({ pathname, query: redirectQuery, ...newTabProps });
                            }
                        }}
                        className={`${record.readState === 0 ? styles.wnTitle : styles.wnUnreadTitle}`}
                    >
                        {record.messageTitle}
                    </p>
                    <Paragraph ellipsis={{ rows: 2 }} style={{ marginBottom: 0 }}>
                        <div
                            // eslint-disable-next-line react/no-danger
                            dangerouslySetInnerHTML={{
                                __html: xss(record.messageContent.replace(/ /g, '&ensp;')) // 解决火狐浏览器空格显示问题
                            }}
                        ></div>
                    </Paragraph>
                </div>
            )
        },
        {
            title: '类型',
            dataIndex: 'noticeResourceName',
            key: 'noticeResourceName',
            width: '30%',
            filters: messageResource,
            filteredValue: typeof query.messageModuleTypes !== 'undefined' ? JSON.parse(query.messageModuleTypes) : [],
            render: text => <span>{text}</span>
        },
        {
            title: '推送时间',
            dataIndex: 'sendTime',
            key: 'sendTime',
            width: '20%'
        }
    ];

    const handleSelectChange = (keys, rows) => {
        const result = rows.map(item => item.businessId);
        setSelectRow(result);
    };

    const rowSelection = {
        selectedRowKeys: selectedRowsIndex,
        onChange: handleSelectChange,
        getCheckboxProps: record => ({
            disabled: record.readState === 1
        })
    };

    useDeepCompareEffect(() => {
        const { rows = [], total = 0 } = userMessage.allNoticeData;
        setAllNoticeData(rows);
        setAllNoticePageTotal(total);
    }, [userMessage.allNoticeData]);

    useDeepCompareEffect(() => {
        const { rows = [], total = 0 } = userMessage.unreadNoticeData;
        setUnreadNoticeData(rows);
        setUnreadNoticePageTotal(total);
    }, [userMessage.unreadNoticeData]);

    useDeepCompareEffect(() => {
        const { rows = [], total = 0 } = userMessage.readNoticeData;
        setReadNoticeData(rows);
        setReadNoticePageTotal(total);
    }, [userMessage.readNoticeData]);

    const dataSource = useMemo(() => {
        switch (activeKey) {
            case 'all':
                return allNoticeData;
            case '0':
                return unreadNoticeData;
            case '1':
                return readNoticeData;
            default:
                return [];
        }
    }, [activeKey, allNoticeData, readNoticeData, unreadNoticeData]);

    const pageTotal = useMemo(() => {
        switch (activeKey) {
            case 'all':
                return allNoticePageTotal;
            case '0':
                return unreadNoticePageTotal;
            case '1':
                return readNoticePageTotal;
            default:
                return 0;
        }
    }, [activeKey, allNoticePageTotal, readNoticePageTotal, unreadNoticePageTotal]);

    return (
        <PageHeaderWrapper>
            <Card bordered={false} className={styles.wnCard} bodyStyle={{ padding: '0 16px' }}>
                <div>
                    <Tabs
                        activeKey={activeKey}
                        size="large"
                        onChange={handleChangedTabs}
                        animated={false}
                        tabBarExtraContent={
                            <>
                                {activeKey !== '1' && (
                                    <Button
                                        style={{ margin: '10px 10px' }}
                                        loading={loading.effects['userMessage/setMarkAsRead']}
                                        disabled={!selectedRow.length}
                                        onClick={() => {
                                            markAsRead(selectedRow);
                                        }}
                                    >
                                        标记为已读
                                    </Button>
                                )}
                                <Button
                                    loading={loading.effects['userMessage/setMarkAllAsRead']}
                                    style={{ margin: '10px 0' }}
                                    onClick={() => {
                                        Modal.confirm({
                                            title: '确定要把消息全部标记为已读吗？',
                                            cancelText: '取消',
                                            okText: '确认',
                                            icon: <Icon type="info-circle" theme="filled" />,
                                            onOk: () => {
                                                markAllAsRead();
                                            }
                                        });
                                    }}
                                >
                                    全部标为已读
                                </Button>
                            </>
                        }
                    >
                        <TabPane
                            tab={`全部${(userMessage?.total || 0) > 0 ? ` (${userMessage?.total})` : ''}`}
                            key="all"
                        />
                        <TabPane
                            tab={`未读${
                                (userMessage?.unReadStateCount || 0) > 0 ? ` (${userMessage?.unReadStateCount})` : ''
                            }`}
                            key="0"
                        />
                        <TabPane tab="已读" key="1" />
                    </Tabs>
                    <Table
                        rowSelection={activeKey === '1' ? undefined : rowSelection}
                        bordered={false}
                        columns={columns}
                        dataSource={dataSource}
                        loading={tabActionLoading}
                        rowKey="businessId"
                        style={{ background: '#fff' }}
                        className={styles.wnTable}
                        pagination={false}
                        onChange={handleTableChange}
                    />
                    <Pagination
                        current={query?.current || 1}
                        pageSize={query?.pageSize || 10}
                        total={pageTotal || 0}
                        onChange={handlePaginationChange}
                    />
                </div>
            </Card>
        </PageHeaderWrapper>
    );
};

export default withRoutePage(
    connect(({ userMessage, loading, menu, global }) => ({
        userMessage,
        menu,
        global,
        loading
    }))(Message)
);
